/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prefer-const */
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
import { StateMachine } from "../FSMBase/FSMBase";

const { ccclass, property } = cc._decorator;

// 1. 定义状态枚举
enum AnimState {
    None = 'None',
    Play = 'Play',
    Wait = 'Wait',
    UP = 'UP', // 新增状态：动画上升
    Finish = 'Finish'
}

@ccclass
export default class PopupGuardStory extends cc.Component {
    @property(cc.Node)
    private story: cc.Node = null;

    @property({ type: cc.Node, tooltip: "滚动视图" })
    scrollView: cc.Node = null;

    // 2. 创建状态机实例
    fsm: StateMachine<AnimState, string> = new StateMachine<AnimState, string>();

    protected start(): void {
        this.init();
    }

    public init() {
        this.scrollOff();

        // 3. 配置状态机
        this.fsm.addState(AnimState.None, {
            onEnter: () => {
                console.log('动画未开始');
            }
        })
            .addState(AnimState.Play, {
                onEnter: () => {
                    console.log('播放动画');
                    if (this.index == 0) {
                        this.playAnimEnter();
                    } else {
                        this.fsm.trigger('up');
                    }

                },
                onUpdate: (dt) => {
                    // 动画播放中的逻辑
                }
            })
            .addState(AnimState.Wait, {
                onEnter: () => {
                    console.log('等待动画');
                    if (this.index >= this.m_items.length) {
                        this.fsm.trigger('finish');
                    }
                },
                onUpdate: (dt) => {
                    if (this.index >= this.m_items.length) return;
                    this.aniTime += dt;
                    if (this.aniTime >= 0.8) {
                        this.aniTime = 0;
                        this.fsm.trigger('nextFrame'); // 触发下一帧事件
                    }
                }
            })
            .addState(AnimState.UP, {
                onEnter: () => {
                    console.log('动画上升');
                    this.upanim();
                }
            })
            .addState(AnimState.Finish, {
                onEnter: () => {
                    console.log('动画完成');
                    this.playTipLabel();
                }
            });

        // 4. 配置转换规则
        this.fsm.addTransition(AnimState.None, AnimState.Play, 'start')
            .addTransition(AnimState.Play, AnimState.Wait, 'wait')
            .addTransition(AnimState.Wait, AnimState.Play, 'nextFrame')
            .addTransition(AnimState.Play, AnimState.UP, 'up') // 新增转换规则：从 Play 到 UP
            .addTransition(AnimState.Wait, AnimState.Finish, 'finish');

        // 5. 初始化状态
        this.fsm.setState(AnimState.None);
        this.initItems();
    }

    update(dt: number) {
        this.fsm.update(dt);
    }

    onClicked() {
        if (this.fsm.currentState === AnimState.Wait) {
            this.fsm.trigger('up');
        }
    }

    private m_items: cc.Node[] = [];
    private posY: number = 0;
    index = 0;
    aniTime = 0;

    initItems() {
        this.m_items = [];
        for (let i = 0; i < this.story.children.length; i++) {
            this.story.children[i].active = false;
            this.m_items.push(this.story.children[i]);
        }
        this.fsm.trigger('start'); // 触发动画开始事件
    }

    playAnimEnter(callback?: Function) {
        const index = this.index;
        const item = this.m_items[index];
        if (index < this.m_items.length - 1) {
            const item1 = this.m_items[index + 1];
            this.posY += item1.height + item.height / 2;
            this.posY = -item1.y + item1.height / 2 - 55 * (index + 1);
        }

        this.animEnter(item, index % 2 === 0, callback);
    }

    animEnter(node: cc.Node, isLeft: boolean, callback?: Function) {
        node.active = true;
        node.scale = 0.8;
        let leftNum = 0;
        let rightNum = 0;
        if (isLeft) {
            node.x = 760;
            leftNum = -8;
            rightNum = 4;
        } else {
            node.x = -760;
            leftNum = 8;
            rightNum = -4;
        }
        cc.tween(node)
            .to(5 / 30, { position: cc.v3(leftNum, node.y), scale: 1 }, { easing: 'quadIn' })
            .to(4 / 30, { position: cc.v3(rightNum, node.y) })
            .to(3 / 30, { position: cc.v3(0, node.y) })
            .call(() => {
                this.index += 1;
                this.fsm.setState(AnimState.Wait); // 切换到等待状态
                if (callback) {
                    callback();
                }
            })
            .start();
    }
    upanim() {
        if (this.index >= this.m_items.length) return;
        let t = cc.tween;
        if (this.index < this.m_items.length - 1) {
            t(this.story)
                .parallel(
                    t()
                        .delay(4 / 30)
                        .call(() => {
                            this.playAnimEnter();
                        })
                    ,
                    t()
                        .to(6 / 30, { // 1~5帧（4帧时间）
                            position: cc.v3(0, this.posY)
                        })
                )
                .start();
        } else {
            this.playAnimEnter(() => {
                this.playTipLabel();
            });
        }
    }

    playTipLabel() {
        this.scrollOn();
    }

    scrollOff() {
        this.scrollView.removeComponent(cc.ScrollView);
    }

    scrollOn() {
        const view = this.scrollView.addComponent(cc.ScrollView);
        view.content = this.story;
        view.vertical = true;
        view.horizontal = false;
        view.inertia = true;
        view.brake = 0.75;
        view.elastic = true;
        view.bounceDuration = 0.23;
    }
}